package com.dataeco.api.service.impl;

import com.dataeco.api.entity.User;
import com.dataeco.api.repository.UserRepository;
import com.dataeco.api.service.EmailService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


@Service
@Transactional
public class EmailServiceImpl extends BaseServiceImpl implements EmailService {
    private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);
    private static final String PRODUCT_SIGN = "生产环境";

    @Value("${c.mail.system.default.from}")
    private String systemDefaultFrom;
    @Value("${c.mail.system.default.to}")
    private String systemDefaultTo;
    @Value("${c.mail.app-deliver.default.to}")
    private String deliverEmailDefaultTo;
    @Value("${c.mail.system.app-deliver.subject}")
    private String appDeliverSubject;
    @Value("${c.mail.system.new-user.subject}")
    private String newUserSubject;
    @Value("${c.mail.system.new-user.from}")
    private String newUserFrom;
    @Value("${c.mail.system.new-user.to}")
    private String newUserTo;

    @Value("${c.mail.system.new-app.subject}")
    private String newAppSubject;
    @Value("${c.mail.system.new-app.from}")
    private String newAppFrom;
    @Value("${c.mail.system.new-app.to}")
    private String newAppTo;

    @Value("${c.mail.business.default.from}")
    private String businessDefaultFrom;

    @Value("${custom.env}")
    private String env;


    private static final String USER_REGISTER = "【用户注册】";
    private static final String USER_REGISTER2_zh = "欢迎使用dataeco平台";
    private static final String USER_RESET_zh = "dataeco平台密码重置";
    private static final String USER_REGISTER2_en = "Welcome to dataeco platform";
    private static final String USER_RESET_en = "dataeco platform password reset";
    private static final String USER_REGISTER2_tw = "歡迎使用dataeco平臺";
    private static final String USER_RESET_tw = "dataeco平臺密碼重置";
    private final UserRepository userRepository;



    private final JavaMailSender mailSender;
    private final TemplateEngine templateEngine;
    private final MessageSource messageSource;


    @Autowired
    public EmailServiceImpl(UserRepository userRepository,
                            JavaMailSender mailSender, TemplateEngine templateEngine, MessageSource messageSource) {
        this.userRepository = userRepository;
        this.mailSender = mailSender;
        this.templateEngine = templateEngine;
        this.messageSource = messageSource;
    }


    @Override
    public void notifyForNewUser(String email) {
        String from = StringUtils.isNotBlank(newUserFrom) ? newUserFrom : systemDefaultFrom;
        String to = StringUtils.isNotBlank(newUserTo) ? newUserTo : systemDefaultTo;
        User user = this.userRepository.findByEmail(email);
        Context context = new Context();
        context.setVariable("user", user);
        String content = templateEngine.process("mail-templates/system/new-user", context);
        String subject = "";
        if (newUserSubject.contains(PRODUCT_SIGN)) {
            subject = USER_REGISTER + user.getCompany();
        } else {
            subject = newUserSubject + user.getCompany();
        }
        sendHtmlMail(from, to, subject, content);
    }

    @Async
    @Override
    public void nodifyForNewApp(String appId) {
//        String from = StringUtils.isNotBlank(newAppFrom) ? newAppFrom : systemDefaultFrom;
//        String to = StringUtils.isNoneBlank(newAppTo) ? newAppTo : systemDefaultTo;
//        App app = this.appRepository.findOne(appId);
//        Context context = new Context();
//        TbAppCategories tbAppCategories = this.tbAppCategoriesService.findById(app.getCategoryId());
//        if (!Objects.isNull(tbAppCategories)) {
//            String name = tbAppCategories.getName();
//            context.setVariable("name", name);
//        }
//        context.setVariable("app", app);
//        User user = this.userRepository.findOne(app.getUser().getId());
//        context.setVariable("user", user);
//        List<AppChannel> acs = this.appChannelRepository.findByAppId(appId);
//        List<Map<String, String>> relatedChannels = Lists.newArrayList();
//        for (AppChannel appChannel : acs) {
//            Channel c = this.channelRepository.findOne(appChannel.getPk().getChannel().getId());
//            Map<String, String> ch = Maps.newHashMap();
//            ch.put("channelName", c.getNameCn());
//            ch.put("channelNameEn", c.getNameEn());
//            ch.put("channelCode", c.getCode());
//            ch.put("packageName", appChannel.getPackageName());
//            ch.put("storeUrl", appChannel.getStoreUrl());
//            relatedChannels.add(ch);
//        }
//        context.setVariable("relatedChannels", relatedChannels);
//        String content = templateEngine.process("mail-templates/system/new-app", context);
//        String subject = "";
//        if (newAppSubject.contains(PRODUCT_SIGN)) {
//            subject = APP_REGISTER + app.getName() + "-" + app.getStage() + "-" + user.getCompany();
//        } else {
//            subject = newAppSubject + app.getName() + "-" + app.getStage() + "-" + user.getCompany();
//        }
//        sendHtmlMail(from, to, subject, content);
    }

    @Override
    public void notifyForAppDeliver(String appId) {
//        String from = systemDefaultFrom;
//        String to = deliverEmailDefaultTo;
//        App app = this.appRepository.findOne(appId);
//        Context context = new Context();
//        TbAppCategories tbAppCategories = this.tbAppCategoriesService.findById(app.getCategoryId());
//        if ((!Objects.isNull(tbAppCategories)) && (!Objects.isNull(app))) {
//            if (tbAppCategories.getId() == app.getCategoryId()) {
//                app.setCategoryId(tbAppCategories.getId());
//            }
//        }
//        context.setVariable("app", app);
//        User user = this.userRepository.findOne(app.getUser().getId());
//        context.setVariable("user", user);
//        List<AppChannel> acs = this.appChannelRepository.findByAppId(appId);
//        List<Map<String, String>> relatedChannels = Lists.newArrayList();
//        String apkId = app.getApkId();
//        Attach attach = new Attach();
//        if (!Objects.isNull(apkId)) {
//            attach = this.attachRepository.findOne(apkId);
//        }
//        for (AppChannel appChannel : acs) {
//            Channel c = this.channelRepository.findOne(appChannel.getPk().getChannel().getId());
//            Map<String, String> ch = Maps.newHashMap();
//            ch.put("channelId", c.getId());
//            ch.put("channelName", c.getNameCn());
//            ch.put("channelNameEn", c.getNameEn());
//            ch.put("channelCode", c.getCode());
//            ch.put("packageName", app.getPackageName());
//            String name = "";
//            if (!Objects.isNull(attach)) {
//                name = attach.getName();
//            }
//            ch.put("name", name);
//            if (this.STAGE_APPSTORE.equalsIgnoreCase(app.getStage()) || this.STAGE_GOOGLEPLAY.equalsIgnoreCase(app.getStage())) {
//                ch.put("storeUrl", appChannel.getStoreUrl());
//            }
//            if (this.STAGE_CHINA_ANDROID.equalsIgnoreCase(app.getStage())) {
//                if (("".equalsIgnoreCase(name)) || Objects.isNull(name)) {
//                    ch.put("storeUrl", DEFAULT_EMAIL_TISHEN);
//
//                } else {
//                    ch.put("storeUrl", name);
//                }
//            }
//            relatedChannels.add(ch);
//        }
//        context.setVariable("relatedChannels", relatedChannels);
//        String content = templateEngine.process("mail-templates/system/deliver-email", context);
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String time = simpleDateFormat.format(System.currentTimeMillis());
//        String subject = "";
//        if (appDeliverSubject.contains(PRODUCT_SIGN)) {
//            subject = APP_DELIVER + app.getName() + " - " + app.getStage();
//        } else {
//            subject = appDeliverSubject + app.getName() + " - " + app.getStage();
//        }
//        sendHtmlMail(from, to, subject, content);
    }

    @Override
    public void notifyForNewUserPassword(String email, String internationalization, String qq) {

        String from = StringUtils.isNotBlank(newUserFrom) ? newUserFrom : systemDefaultFrom;
        String to = email;
        String emailEncode = "";
        String qqEncode = "";
        String internationalizationEncode = "";
        try {
            emailEncode = URLEncoder.encode(email, "utf-8");
            qqEncode = URLEncoder.encode(qq, "utf-8");
            internationalizationEncode = URLEncoder.encode(internationalization, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String webUrl = "http://dashboard" + env + ".dataeco.com/#/setpwd?email=" + emailEncode + "&qq=" + qqEncode;
        Context context = new Context();
        context.setVariable("webUrl", webUrl);
        context.setVariable("internationalization", internationalization);
        String content = templateEngine.process("mail-templates/system/register-password", context);
        String subject = "";
        if (!StringUtils.isEmpty(internationalization)) {
            if ("zh".equalsIgnoreCase(internationalization)) {
                subject = USER_REGISTER2_zh;
            }

            if ("en".equalsIgnoreCase(internationalization)) {
                subject = USER_REGISTER2_en;
            }

            if ("tw".equalsIgnoreCase(internationalization)) {
                subject = USER_REGISTER2_tw;
            }
        }
        sendHtmlMail(from, to, subject, content);
    }

    @Override
    public void notifyForResetPassword(String email, String internationalization) {
        String from = StringUtils.isNotBlank(newUserFrom) ? newUserFrom : systemDefaultFrom;
        String to = email;
        String emailEncode = "";
        String qqEncode = "";
        String internationalizationEncode = "";
        try {
            emailEncode = URLEncoder.encode(email, "utf-8");
            internationalizationEncode = URLEncoder.encode(internationalization, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String webUrl = "http://dashboard" + env + ".dataeco.com/#/resetpwd?email=" + emailEncode;
        Context context = new Context();
        context.setVariable("webUrl", webUrl);
        context.setVariable("internationalization", internationalization);
        String content = templateEngine.process("mail-templates/system/reset-password", context);
        String subject = "";
        if (!StringUtils.isEmpty(internationalization)) {
            if ("zh".equalsIgnoreCase(internationalization)) {
                subject = USER_RESET_zh;
            }

            if ("en".equalsIgnoreCase(internationalization)) {
                subject = USER_RESET_en;
            }

            if ("tw".equalsIgnoreCase(internationalization)) {
                subject = USER_RESET_tw;
            }
        }
        sendHtmlMail(from, to, subject, content);

    }


    private void sendHtmlMail(String from, String to, String subject, String content) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setSubject(subject);
            String[] recipients = to.split(";");
            helper.setTo(recipients);
            String[] sender = from.split(":");
            if (sender.length > 1) {
                helper.setFrom(sender[0], sender[1]);
            } else {
                helper.setFrom(sender[0]);
            }
            helper.setText(content, true);
            mailSender.send(helper.getMimeMessage());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            String info = String.format("Subject: %s%nFrom: %s%nTo: %s%nContent:%n%s%n", subject, from, to, content);
            logger.warn(info);
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
        }
    }
}
